//
// Created by lz on 2021/2/23.
//

#ifndef MYWEBLIB_BASE_THREAD_H_
#define MYWEBLIB_BASE_THREAD_H_

#include "base/Atomic.h"
#include "base/Types.h"
#include "base/CountDownLatch.h"

#include <functional>
#include <memory>
#include <pthread.h>

namespace lzweb
{
	class Thread : noncopyable
	{
	 public:
		using ThreadFunc = std::function<void()>;

		explicit Thread(ThreadFunc, const string& name = string());
		// FIXME: make it movable in C++11
		~Thread();

		void start();

		int join();

		bool started() const
		{
			return started_;
		}

		pid_t tid() const
		{
			return tid_;
		}
		//返回引用？
		const string& name() const
		{
			return name_;
		}

		static int numCreated() { return numCreated_.get(); }

	 private:
		void setDefaultName();

		bool started_;
		bool joined_;
		pthread_t pthreadId_;   //由进程管理的线程tid
		pid_t tid_;             //由内核管理的线程pid
		ThreadFunc func_;
		string name_;
		CountDownLatch latch_;    //该成员通过条件变量进行线程间同步，在此是保证主线程和新线程的代码同步

		static AtomicInt32 numCreated_;  //用来标志目前有多少个线程？

	};

}//namespace lzweb



#endif //MYWEBLIB_BASE_THREAD_H_
